import RNFetchBlob from "rn-fetch-blob";
import { save } from "@react-native-community/cameraroll";
import { check, PERMISSIONS, request } from "react-native-permissions";
import { Clipboard, Linking, Dimensions, Platform, Vibration } from "react-native";
import { userStore } from "../store";
import Sound from "react-native-sound";
import ToastUtils from "./ToastUtils";
import moment from "moment";
import DeviceInfo from "react-native-device-info";
import { hotUpgradeVersionCode } from "../configs";
import uuid from "uuid";
import { toJS } from "mobx";
import { Geolocation } from 'react-native-amap-geolocation';
import { reportLocation } from '../net/common'
import backgroundTimePlugin from "../plugins/backgroundTimer";

export function logger(...args) {
  if (__DEV__) {
    console.log('[deliveryapp] [logger] ', ...args);
  }
}

export async function downLoadImage(imgUrl) {
  let index = imgUrl.lastIndexOf(".");
  let ext = imgUrl.substr(index + 1);
  const res = await RNFetchBlob
    .config({ fileCache: true, appendExt: ext })
    .fetch("GET", imgUrl)
    .catch(e => logger("下载错误", e));
  logger("下载片完成", res.path());
  if (res.path()) {
    const result = await save(res.path(), {
      type: "photo",
      album: "chat",
    }).catch((error) => logger("保存失败,", error));
    logger("下载图片结果", result);
    return result;
  }
  return null;
};

/**
 * 检测存储权限
 * @returns {Promise<boolean>}
 */
export async function checkStorePermission() {
  //1.检测定位权限
  let store_permission = await check(Platform.select({
    android: PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE,
    ios: PERMISSIONS.IOS.PHOTO_LIBRARY,
  })).catch(logger);
  //2.无权限，则请求获取群贤
  if (store_permission !== "granted") {
    store_permission = await request(Platform.select({
      android: PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE,
      ios: PERMISSIONS.IOS.PHOTO_LIBRARY,
    })).catch(logger);
  }
  logger("获取存储权限", store_permission);
  if (store_permission === "granted") {
    return true;
  } else {
    return false;
  }
};

export async function checkRecordPermission() {
  //1.检测麦克风权限
  let store_permission = await check(Platform.select({
    android: PERMISSIONS.ANDROID.RECORD_AUDIO,
    ios: PERMISSIONS.IOS.MICROPHONE,
  })).catch(logger);
  //2.无权限，则请求获取群贤
  if (store_permission !== "granted") {
    store_permission = await request(Platform.select({
      android: PERMISSIONS.ANDROID.RECORD_AUDIO,
      ios: PERMISSIONS.IOS.MICROPHONE,
    })).catch(logger);
  }
  logger("获取麦克风权限", store_permission);
  if (store_permission === "granted") {
    return true;
  } else {
    return false;
  }
};

/**
 * 检测相机权限
 * @returns {Promise<boolean>}
 */
export async function checkCameraPermission() {
  //1.检测定位权限
  let location_permission = await check(Platform.select({
    android: PERMISSIONS.ANDROID.CAMERA,
    ios: PERMISSIONS.IOS.CAMERA,
  })).catch(logger);
  //2.无权限，则请求获取
  if (location_permission !== "granted") {
    location_permission = await request(Platform.select({
      android: PERMISSIONS.ANDROID.CAMERA,
      ios: PERMISSIONS.IOS.CAMERA,
    })).catch(logger);
  }
  if (location_permission === "granted") {
    return true;
  } else {
    return false;
  }
};

export async function checkMultiPermission() {
  const hasCameraPermission = await checkCameraPermission();
  const hasStorePermission = await checkStorePermission();
  return (hasCameraPermission && hasStorePermission);
};

export async function checkRecordAndStorePermission() {
  const hasRecordPermission = await checkRecordPermission();
  const hasStorePermission = await checkStorePermission();
  return (hasRecordPermission && hasStorePermission);
};

/**
 * 申请定位权限
 * @returns
 */
export async function checkLocationPermission() {
  //1.检测定位权限
  let location_permission = await check(Platform.select({
    android: PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
    ios: PERMISSIONS.IOS.LOCATION_ALWAYS,
  })).catch(logger);
  //2.无权限，则请求获取
  if (location_permission !== "granted") {
    location_permission = await request(Platform.select({
      android: PERMISSIONS.ANDROID.ACCESS_FINE_LOCATION,
      ios: PERMISSIONS.IOS.LOCATION_ALWAYS,
    })).catch(logger);
  }
  if (location_permission === "granted") {
    return true;
  } else {
    return false;
  }
}

/**
 * 申请后台定位权限
 * @returns
 */
 export async function checkBgLocationPermission() {
  //1.检测定位权限
  let location_permission = await check(Platform.select({
    android: PERMISSIONS.ANDROID.ACCESS_BACKGROUND_LOCATION,
    ios: PERMISSIONS.IOS.LOCATION_ALWAYS,
  })).catch(logger);
  //2.无权限，则请求获取
  if (location_permission !== "granted") {
    location_permission = await request(Platform.select({
      android: PERMISSIONS.ANDROID.ACCESS_BACKGROUND_LOCATION,
      ios: PERMISSIONS.IOS.LOCATION_ALWAYS,
    })).catch(logger);
  }
  if (location_permission === "granted") {
    return true;
  } else {
    return false;
  }
}

export function getUriImage(uri) {
  return uri !== null && uri !== undefined && uri.includes("/") && uri.includes(".") ? uri : "";
}

const DESIGN_WIDTH = 750;
export const SCREEN_WIDTH = Dimensions.get("window").width;
export const SCREEN_HEIGHT = Dimensions.get("window").height;

// 转换字体大小
export function transformSize(designSize) {
  const number = (designSize / DESIGN_WIDTH) * SCREEN_WIDTH;
  let remainder = number % 1;
  const int = number - remainder;
  remainder =
    0.25 <= remainder && remainder < 0.75 ? 0.5 : Math.round(remainder);
  return int + remainder;
}

/**
 * 字母比较
 * @param property
 * @returns {function(*, *): number}
 */
export function compare(property) {
  return function(a, b) {
    var x1 = a[property];
    var x2 = b[property];
    if (x1 < x2) {
      return -1;
    }
    if (x1 > x2) {
      return 1;
    }
    return 0;
  };
}

export function compareData(p) { //这是比较函数
  return function(m, n) {
    var a = m[p];
    var b = n[p];
    return a - b; //升序
  };
}

export function isLetters(str) {
  var re = /^[A-Za-z]+$/;
  if (str.match(re) == null)
    return false;
  else
    return true;
}

export function isNumber(str) {
  var re = /^[0-9]+$/;
  if (str.match(re) == null)
    return false;
  else
    return true;
}

/***
 * 限制两位小数
 * @param str
 * @returns {boolean}
 */
export function limit2(str) {
  return str.replace(/[^0-9.]+/, "").replace(".", "$#$").replace(/\./g, "").replace("$#$", ".").replace(/^(\-)*(\d+)\.(\d\d).*$/, "$1$2.$3");
}

/***
 * 消息震动
 */
export function vibrate() {
  if (userStore.shock == true) {
    Vibration.vibrate();
  }
}

/**
 * 消息声音通知
 */
export function sound() {
  if (userStore.sound == true) {
    soundPlay("http://liaole.oss-cn-shenzhen.aliyuncs.com/audio/ddd.mp3");
  }
}

async function soundPlay(source) {

  // logger("播放声音", "加载资源" + source)
  let whoosh = new Sound(source, null, (error) => {
    // logger("播放声音", "准备好", error)
    if (error) {
      logger("播放声音", "failed to load the sound", error);
      return;
    }
    if (whoosh.isPlaying()) {
      whoosh.stop(() => {
        whoosh.play((success) => {
          if (success) {
            // logger("播放声音", "播放完成")
          } else {
            logger("播放声音", "playback failed due to audio decoding errors");
          }
          whoosh.release();
        });
      });
      return;
    }
    whoosh.play((success) => {
      if (success) {
        // logger("播放声音", "播放完成")
      } else {
        logger("播放声音", "playback failed due to audio decoding errors2");
      }
      whoosh.release();
    });
  });

}

export async function uploadVideo(videoUri, type = "\"video/mp4\"") {
  let paramsVideo = new FormData();
  paramsVideo.append("file", {
    uri: videoUri,
    type,
    name: videoUri.substring(videoUri.lastIndexOf("\/") + 1),
  });

  //上传视频
  const res = await axios.post(api.uploadImage, paramsVideo, {
    headers: {
      "Content-Type": "multipart/form-data",
    },
    showLoading: true,
  }).catch(e => {
    Toast.show("上传失败");
  });
  if (res)
    return {
      thumbnail: `${res.data}?x-oss-process=video/snapshot,t_1000,f_jpg,w_0,h_0,m_fast,ar_auto`,
      videoUrl: res.data,
    };
  return null;
};

/**
 * 经纬度转地址
 * @param lat
 * @param lng
 * @returns {Promise<any>}
 */
export function geo2Adr(lat, lng) {
  // logger('百度解析',lat, lng)
  return new Promise(function(resolve, reject) {
    let url = `http://api.map.baidu.com/geocoder?output=json&coordtype=gcj02ll&ret_coordtype=gcj02ll&location=${lat},${lng}&key=37492c0ee6f924cb5e934fa08c6b1676`;
    fetch(url, {
      method: "Get",
    }).then((response) => response.json())
      .then((response) => {
        logger("百度地址：", url, JSON.stringify(response));
        if ("OK" === response.status) {
          // logger(JSON.stringify(response.result));
          const { province, city, district } = response.result.addressComponent;
          const { lng, lat } = response.result.location;
          resolve({
            province,
            city,
            district,
            address: response.result.formatted_address,
            longitude: lng,
            latitude: lat,
          });
        } else {
          reject(null);
        }
      })
      .catch((err) => {
        logger("百度解析报错", err);
        reject(err);
      });
  });
}

/**
 * 复制内容
 * @param msg
 */
export const setClipboardContent = (msg) => {
  Clipboard.setString(msg);
  ToastUtils.showInfo("复制成功");
};
/**
 * 拨打电话
 * @param tel
 */
export const call = (phone,ordNo=null) => {
  logger('点击拨打电话',phone,ordNo)
  Linking.canOpenURL(`tel:${phone}`)
    .then((supported) => {
    if (!supported) {
      ToastUtils.showFailInfo("无法拨打");
    } else {
      if(!IsNullOrEmpty(ordNo))
      {
        addCallLog(ordNo,phone)
      }
      phone = phone.replace(/_[\s\S]+/, '')
      return Linking.openURL(`tel:${phone}`);
    }
  }).catch(error => console.log("tel error", error));
};

/**
 * 增加拨打手机号码日志
 * @param ordNo
 * @param phone
 */
export const addCallLog = (ordNo, phone) => {
  try {
    let params = {
      ordNo,
      phone,
    };
    axios.get(api.addCallLog, { params })
      .then(res => {

      })
      .catch(logger);
  } catch (e) {
  }
};

/**
 * 上传失败日志
 * @param order_no
 * @param content
 */
export const uploadError = (eventName, data) => {
  try {
    let content = `版本号：v${DeviceInfo.getVersion()}.${hotUpgradeVersionCode}
    \n系统：${DeviceInfo.getSystemName()},${DeviceInfo.getSystemVersion()}
    \n时间：${moment().format("YYYY-MM-DD HH:mm:ss")}
    \n配送员：${userStore.userInfo && userStore.userInfo.name},${userStore.userInfo && userStore.userInfo.distributorId}
    \n网络状态：${netState}
    \n${data}`;
    let params = {
      token: global.token,
      eventName,
      content,
      showLoading: true,
    };
    axios.get(api.uploadError, { params })
      .then(res => {
        // let list=toJS(userStore.errorLog)
        // list.push({eventName,content,time:moment().format("YYYY-MM-DD HH:mm:ss"),id:uuid()})
        // userStore.setValue('errorLog',list)
      })
      .catch(e => {
        logger("上传失败日志error", e);
        let list = toJS(userStore.errorLog);
        list.push({ eventName, content, time: moment().format("YYYY-MM-DD HH:mm:ss"), id: uuid() });
        userStore.setValue("errorLog", list);
      });
  } catch (e) {
  }
};

export const getCurrentPosition = () => {
  return new Promise(resolve => {
    Geolocation.getCurrentPosition(({ coords }) => {
      resolve(coords)
    })
  })
}

/**
 * 上传经纬度
 * @param {*} isOpen 
 */
export const setUploadLocationTimer = async (isOpen, time, callback) => {
  if (isOpen) {
    backgroundTimePlugin.setTimer({
      key: 'uploadLocationInterval',
      type: 'interval',
      time: time || 60 * 1000,
      callback: async () => {
        const { userInfo } = userStore;
        const coords = await getCurrentPosition()
        if (!userInfo.name || !coords.longitude || !coords.latitude) {
          return
        }
        const params = {
          account: userInfo.name,
          accountPhone: userInfo.telNo,
          longitude: coords.longitude,
          latitude: coords.latitude,
          altitude: coords.altitude || 60,
        }
        logger("[setUploadLocationTimer][上报定位]：", params)
        reportLocation(params).then(res => {
          logger('返回数据：', JSON.stringify(res))
        })
      },
    })
  } else {
    logger("[setUploadLocationTimer][停止上报定位]：")
    backgroundTimePlugin.remove({key: 'uploadLocationInterval', type: 'interval'})
  }
}

/**
 * 打开url
 * @param {*} param0 
 */
export const openURL = ({url} = {}) => {
  Linking.canOpenURL(url).then(res => {
    if (res) {
      return Linking.openURL(url).catch(Log);
    } else {
      ToastUtils.showInfo(`打开网址：${url} 异常`);
    }
  }).catch(e => Log(e.message));
}